<template>
  <div class="login_wrapper">
    <!-- 登录与修改密码  -->
    <el-form
      :model="form"
      :rules="rulesLogin"
      ref="form"
      label-position="left"
      label-width="0px"
      class="demo-ruleForm card-box loginform"
    >
      <h3 class="title">{{title}}</h3>
      <el-form-item prop="staffNum" class="marB30 txt_wrapper" v-show="isShowLogin">
        <el-input
          type="text"
          ref="staffNum"
          v-model.trim="form.staffNum"
          maxlength="6"
          placeholder="请输入工号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password" class="marB30 txt_wrapper" v-show="isShowLogin">
        <el-input type="password" ref="password" v-model.trim="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item prop="newPassword" class="marB30 txt_wrapper" v-if="isShowLogin === false">
          <p class="tipNewPwd">新密码</p>
        <el-input
          type="password"
          ref="newPassword"
          v-model.trim="form.newPassword"
          placeholder="请输入新密码"
        ></el-input>
      </el-form-item>
      <el-form-item prop="reNewPassword" class="marB30 txt_wrapper" v-if="isShowLogin === false">
          <p class="tipRepeatPwd">重复密码</p>
        <el-input
          type="password"
          ref="reNewPassword"
          v-model.trim="form.reNewPassword"
          placeholder="请再次输入新密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <p class="change_pwd" @click.stop="changeInterface(1)" v-show="isShowLogin && !loading">{{txt}}</p>
        <p class="change_pwd" @click.stop="changeInterface(2)" v-show="!isShowLogin">{{txt}}</p>
      </el-form-item>
      <el-form-item style="width:100%;" class="login_btn_wrapper">
        <el-button
          class="login_btn"
          type="primary"
          style="width:100%;"
          v-loading="loading"
          @click.native.prevent="sureLogin"
          :disabled="loading"
          v-if="isShowLogin"
        >{{loginBtnTxt}}</el-button>
        <el-button
          class="login_btn"
          type="primary"
          style="width:100%;"
          v-loading="changeLoading"
          @click.native.prevent="sureChangePwd"
          :disabled="changeLoading"
          v-else
        >{{changeLoading ? '修改中...' : '确定修改'}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import http from "@/assets/js/http"
import moment from "moment"
import Lockr from "lockr"
import Cookies from "js-cookie"
import _g from "@/assets/js/global"
import config from "@/assets/js/config.js"
import { validateNumLetters, validateNum,validateCapital } from "@/assets/js/common.js"



export default {
  data() {
    // 验证密码
    let validatePwd = (rule, value, callback) => {
      if (!validateNumLetters(value)) {
        callback(new Error("请输入数字值"))
      }else{
        callback()
      }
    }
     // 验证工号
    let validateStaffNum = (rule, value, callback) => {
        const firstChar = value.slice(0,1)
        if(!validateCapital(firstChar)){
            callback(new Error("首字符为大写字母"))
        }
        const str = value.slice(1)
        if (!validateNum(str)) {
            callback(new Error("请输入数字值"))
        }else{
            callback()
        }
    }
    // 校验密码是否相同
    var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.form.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
      // 校验新密码是否与旧密码相同
    // var validatePwdNotEqual2 = (rule, value, callback) => {
    //     const password = this.form.password
    //     if ('' !== password && value === password) {
    //       callback(new Error('新旧密码不能相同!'));
    //     } else {
    //       callback();
    //     }
    //   }

    return {
      isShowLogin: true,          //  是否显示登录界面，默认显示登录界面
      loading: false,                   //  登录中
      changeLoading: false,                   //  密码修改中
      userId:null,                      //  登录人员id
      loginBtnTxt:'登录',
      remTime:0,                  //  倒计时
      form: {
        staffNum: "", // ..工号
        password: "", // ..密码,
        newPassword: "", // ..新密码
        reNewPassword: "" // ..重复输入的新密码
      },
      rulesLogin: {
        staffNum: [
          {
            required: true,
            message: "请输入工号",
            trigger: "blur"
          },
          {
            min: 6,
            max: 6,
            message: "工号必须为6位",
            trigger: "blur"
          },
          {
            validator: validateStaffNum,
            message: "工号必须为首字母大写加5位数字",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          },
          {
            min: 6,
            max: 50,
            message: "密码至少6位",
            trigger: "blur"
          },
          {
            validator: validatePwd,
            message: "密码只能是数字和字母",
            trigger: "blur"
          }
        ],
        newPassword: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          },
          {
            min: 6,
            max: 50,
            message: "密码至少6位",
            trigger: "blur"
          },
          {
            validator: validatePwd,
            message: "密码只能是数字和字母",
            trigger: "blur"
          },
        //   {
        //     validator: validatePwdNotEqual2,
        //     trigger: "blur"
        //   }
        ],
        reNewPassword: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          },
          {
            min: 6,
            max: 50,
            message: "密码至少6位",
            trigger: "blur"
          },
          {
            validator: validatePwd,
            message: "密码只能是数字和字母",
            trigger: "blur"
          },
          {
            validator: validatePass,
            trigger: "blur"
          }
        ]
      }
    }
  },
  computed: {
    title(){                                                //  标题
      let str = ''
      str = this.isShowLogin ?   '用户登录' :  '修改密码';
      return str;
    },
    txt(){
      let str = ''
      str = this.isShowLogin ?   '修改密码' :  '返回登录';
      return str;
    },

  },
  methods: {
    /* 切换登录与修改密码界面的显示与隐藏 */
    changeInterface(type){
      const that = this
      if(type === 1){
        // 在这里请求服务器，传递工号，判断密码是否已被清空，如果被清空，不用显示请输入原密码，置空，需要回传一个字段
        let data = {}
        data.staffNum =  that.form.staffNum
        data.password = that.form.password
        if(data.staffNum === ''){
          _g.toastMsg("warning", '请先输入工号');
          return
        }
        if(data.password  === ''){
            _g.toastMsg("warning", '请先输入密码');
            return
        }else if(data.password.length < 6){
            _g.toastMsg("warning", '密码至少6位');
            return
        }else if(!validateNumLetters(data.password)){
            _g.toastMsg("warning", '密码只能是数字和字母');
            return
        }
        _g.showLoading('账号状态查询中')
        this.apiPost("admin/base/queryAccountStatus", data).then(res => {
                _g.showLoading().close()
                if(typeof res === 'string'){
                  res = JSON.parse(res)
                }
                if (res.code != 200) {
                  this.handleError(res)
                } else {
                   if(res.data.isSuccess === 1 || res.data.isSuccess === 2){
                         that.loginBtnTxt = '登录'
                         _g.toastMsg("error", res.message)
                      }else if(res.data.isSuccess === 3){                           //  帐号锁定或被注销
                          that.loginBtnTxt = '登录'
                          _g.showLoading(res.message,'loginLoading')
                          _g.toastMsg("error", res.message)
                      }else if(res.data.isSuccess === 4){                         //  需要做登录失败次数限制
                        // const loginLastTime = new Date(res.data.login_lasttime).getTime();
                        // const nowTime = new Date().getTime(); 
                        if(res.data.login_count === 5){
                              that.loading = true
                              that.remTime = 60
                              setInterval(function () { 
                                if (that.remTime > 0) {
                                  --that.remTime
                                   that.loginBtnTxt = '剩余时间(' + that.remTime + ')';
                                } else { 
                                  clearInterval()
                                  that.remTime = 0
                                   that.loading = false
                                   that.loginBtnTxt = '登录';
                                }
                              },1000)
                              _g.toastMsg("error", res.message)
                        }else if(res.data.login_count === 10){
                          that.remTime = 180
                           that.loading = true
                           setInterval(function () { 
                                if ( that.remTime > 0) {
                                  -- that.remTime
                                   that.loginBtnTxt = '剩余时间(' +  that.remTime + ')';
                                } else { 
                                  clearInterval()
                                   that.remTime = 0
                                    that.loading = false
                                   that.loginBtnTxt = '登录';
                                }
                              },1000)
                              _g.toastMsg("error", res.message)
                        }else if(res.data.login_count === 15){
                           that.loginBtnTxt = '登录'
                            that.loading = false
                            _g.showLoading(res.message,'loginLoading')
                            _g.toastMsg("error", res.message)
                        }
                      }else if(res.data.isSuccess === 0){                                                                             //  修改成功
                         that.loginBtnTxt = '登录'
                        this.userId = res.data.login_user_id
                        this.isShowLogin = false
                      }
                    }
                //   if(res.data === 1 || res.data === 3){
                //       _g.toastMsg("error", res.message)
                //   }else if(res.data === 5 || res.data === 6){                                 //  账号被锁定或注销
                //     _g.showLoading(res.message,'loginLoading')
                //     _g.toastMsg("error", res.message)
                //   }else{                                                                              //  成功
                //       this.userId = res.data.login_user_id
                //       this.isShowLogin = false
                //   }
                // }
          })
      }else{                                                //  显示登录界面
        this.isShowLogin = true
      }
    },
    /* 登录 */
    sureLogin() {
      const that = this

    let staffNum = ''
    let userName = ''
      // if (this.loading) return
      that.$refs['form'].validate(valid => {
              if (valid) {
                  let data = {}
                  data.staffNum = that.form.staffNum
                  data.password = that.form.password
                  // data.loginUserId = 
                  that.loading = true
                  that.loginBtnTxt = '登录中...'
                  console.log('A')
                  that.apiPost("/admin/base/login", data).then(res => {
                       console.log('B')
                    that.loading = false
                    if(typeof res === 'string'){
                      res = JSON.parse(res)
                    }
                    if (res.code != 200) {
                       that.loginBtnTxt = '登录'
                      that.handleError(res)
                    } else {
                      // this.resetCommonData(res.data)
                      if(res.data.isSuccess === 1 || res.data.isSuccess === 2){
                         that.loginBtnTxt = '登录'
                         _g.toastMsg("error", res.message)
                      }else if(res.data.isSuccess === 3){                           //  帐号锁定或被注销
                          that.loginBtnTxt = '登录'
                        //   _g.showLoading(res.message,'loginLoading')
                          _g.toastMsg("error", res.message)
                      }else if(res.data.isSuccess === 4){                         //  需要做登录失败次数限制
                        // const loginLastTime = new Date(res.data.login_lasttime).getTime();
                        // const nowTime = new Date().getTime(); 
                        if(res.data.login_count === 5){
                              that.loading = true
                              that.remTime = 60
                              setInterval(function () { 
                                if (that.remTime > 0) {
                                  --that.remTime
                                   that.loginBtnTxt = '剩余时间(' + that.remTime + ')';
                                } else { 
                                  clearInterval()
                                  that.remTime = 0
                                   that.loading = false
                                   that.loginBtnTxt = '登录';
                                }
                              },1000)
                              _g.toastMsg("error", res.message)
                        }else if(res.data.login_count === 10){
                          that.remTime = 180
                           that.loading = true
                           setInterval(function () { 
                                if ( that.remTime > 0) {
                                  -- that.remTime
                                   that.loginBtnTxt = '剩余时间(' +  that.remTime + ')';
                                } else { 
                                  clearInterval()
                                   that.remTime = 0
                                    that.loading = false
                                   that.loginBtnTxt = '登录';
                                }
                              },1000)
                              _g.toastMsg("error", res.message)
                        }else if(res.data.login_count === 15){
                           that.loginBtnTxt = '登录'
                            that.loading = false
                            _g.showLoading(res.message,'loginLoading')
                            _g.toastMsg("error", res.message)
                        }
                      }else if(res.data.isSuccess === 0){                                                                             //  登录成功
                        // Cookies.set('userId',res.data.login_user_id)
                        staffNum = res.data.staffnum
                        userName = res.data.user_name === null ? '/' : res.data.user_name

                         that.loginBtnTxt = '登录'
                         
                        //  存储权限
                        that.$store.dispatch('setRoles',res.data.power)
                        
                        // 承诺履历基本信息状态
                        Cookies.set('userPromise',res.data.user_promise)

                        // 本地存储用户名
                        Cookies.set('userName',res.data.user_name === null ? '未知' : res.data.user_name)

                        // 本地存储登录用户id
                        Cookies.set('loginUserId',res.data.login_user_id)

                        // 本地存储工号
                        Cookies.set('staffNum',res.data.staffnum)

                        that.$store.dispatch('setUserName',res.data.user_name)
                        that.$store.dispatch('setUserStaffNum',res.data.staffnum)
                        that.$store.dispatch('setLoginUserId',res.data.login_user_id)

                        if(res.data.photoPath != null){//  如果存在头像照片
                             that.$store.dispatch('setPhotoPath',res.data.photoPath)
                        }

                        // 本地存储履历基本信息是否全部填写完毕
                        // Cookies.set('isFinishedReMsg',res.data.isFinishedReMsg)
                        that.$store.dispatch('setFinishedReMsg',res.data.isFinishedReMsg)

                        // // 存储普通用户 / 管理员判别标识
                        // that.$store.dispatch('setIsAdmin',false)
                        

                        // this.$store.dispatch('setToken',Cookies.get('PHPSESSID'))
                        //  _g.toastMsg("success", res.message)
console.log(res)
                        // 如果有权限，需要如下判断，如果没有权限，则直接跳转guest/welcome
                        if(res.data.user_promise == 1){                                                                           //  如果已经承诺
                            // that.$router.push('/admin/welcome')

                            // that.$confirm('请选择进入的页面', '提示', {
                            //     confirmButtonText: '管理员页面',
                            //     cancelButtonText: '普通用户',
                            //     type: 'warning',
                            //     center: true
                            // }).then(() => {
                            //     that.$store.dispatch('setIsAdmin',true)
                            //     that.$router.push('/admin/welcome')
                            // }).catch(() => {
                            //     that.$store.dispatch('setIsAdmin',false)
                            //     that.$router.push('/guest/welcome')
                            // });

                            that.$router.push('/guest/welcome')
                            // that.$router.push('https://www.baidu.com//')
                        }else if(res.data.user_promise == 2){                                                                                                                  //  如果没有承诺
                            that.$router.push( '/addResume')
                        }
                      }
                    }
                  })
          } else {
                 that.loginBtnTxt = '登录'
                that.loading = false
          }
      })
    },

    /* 修改密码 */
    sureChangePwd(){
       this.$refs['form'].validate(valid => {
              if (valid) {
                  let data = {}
                   data.newPassword = this.form.newPassword
                  data.userId = this.userId
                  this.changeLoading = true
                  this.apiPost("/admin/base/setInfo", data).then(res => {
                    this.changeLoading = false
                    if(typeof res === 'string'){
                      res = JSON.parse(res)
                    }
                    if (res.code != 200) {
                      this.handleError(res)
                    } else {
                      // this.resetCommonData(res.data)
                      if(res.data === 1){
                         _g.toastMsg("error", res.message)
                      }else if(res.data === 0){                                                                              //  修改成功
                        this.form.password = this.form.newPassword
                        _g.toastMsg("success", res.message)
                        this.isShowLogin = true                                                                             //  显示登录
                      }
                    }
                  })
          } else {
                this.changeLoading = false
          }
      })
    }
  },
  created() {
    // this.checkIsRememberPwd()
    // this.apiPost('admin/base/getConfigs').then((res) => {
    //   this.handelResponse(res, (data) => {
    //     document.title = data.SYSTEM_NAME
    //     this.systemName = data.SYSTEM_NAME
    //     if (parseInt(data.IDENTIFYING_CODE)) {
    //       this.requireVerify = true
    //       this.rules2.verifyCode[0].required = true
    //     }
    //   })
    // })
    // this.verifyUrl = this.verifyImg
  },
  mounted() {
    // window.addEventListener('keyup', (e) => {
    //   if (e.keyCode === 13) {
    //     this.handleSubmit2('form')
    //   }
    // })
  },
  mixins: [http]
}
</script>

<style>

.login_wrapper{
  width: 100%;
  height: 100%;
  background: url('../../assets/images/bg.jpg') no-repeat left top;
  background-size: cover;
}

.verify-pos {
  position: absolute;
  right: 100px;
  top: 0px;
}

.card-box {
  padding: 20px;
  /*box-shadow: 0 0px 8px 0 rgba(0, 0, 0, 0.06), 0 1px 0px 0 rgba(0, 0, 0, 0.02);*/
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -moz-border-radius: 5px;
  background-clip: padding-box;
  /* margin-bottom: 20px; */
  background-color: #f9fafc;
  /* margin: 120px auto; */
  /* width: 400px; */
  /* border: 2px solid #8492A6; */
}

.title {
  margin-bottom: 35px;
  text-align: center;
  color: #ef8200;
  font-size: 33px;
  line-height: 72px;
}

.loginform {
  max-width: 435px !important;
  width: 32%;
  position: absolute;
  top: 50%;
  right: 9%;
  transform: translate3d(0, -50%, 0);
  box-sizing: border-box;
  padding: 20px;
  border-radius: 0;
}

.change_pwd {
  font-size: 16px;
  color: #b3b3b3;
  text-align: right;
  cursor: pointer;
}

.login_btn_wrapper {
  padding-top: 7px;
  padding-bottom: 75px;
  margin-bottom: 0;
}

.login_btn {
  background-color: #ef8200;
  font-size: 18px;
  border-radius: 0;
  border: none;
  padding: 17px 0;
}

.login_btn:focus,
.login_btn:hover {
  background-color: #f18e19;
}

.tipNewPwd,
.tipRepeatPwd{
    position: relative;
    top: -15px;
    color: #ef8200;
    margin-top: 20px;
    font-size: 14px;
}
</style>



